package com.jiang.realm;


import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.jiang.sevice.MemberLoginService;
import com.jiang.vo.Member;

public class RolePermissionRealm extends AuthorizingRealm {

	// 这里是做用户授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		String username = principals.getPrimaryPrincipal().toString();
		Set<String> roles = new MemberLoginService().getRolesByMid(username);
		Set<String> actions = new MemberLoginService().getActionsByMid(username);
		SimpleAuthorizationInfo authorization = new SimpleAuthorizationInfo();
		authorization.setRoles(roles);
		authorization.setStringPermissions(actions);
		return authorization;
	}

	// 这里是做用户认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		// 获取前端传来的用户名与密码
		String chk_username = token.getPrincipal().toString();
		// 因为使用的不是简单的UsernamePasswordToken，所以获取密码的时候是一个char[]
		String chk_password = new String((char[]) token.getCredentials());
		MemberLoginService service = new MemberLoginService();
		Member member =service.getMember(chk_username);
		// 然后与后台数据库中的数据比较
		if (member != null) {
			if (member.getPassword().equals(chk_password)) {
				service.close();
				return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), "RolePermissionRealm");
			} else {
				service.close();
				throw new IncorrectCredentialsException("密码错误!");
			}
		}else{
			service.close();
			throw new UnknownAccountException("用户名不存在!");
		}
			
	}

}
